package com.qf.shiro2202day02.shiroconfig;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.shiro2202day02.user.entity.User;
import com.qf.shiro2202day02.user.service.UserService;
import jdk.nashorn.internal.parser.Token;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

public class CustomRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user=(User)principalCollection.getPrimaryPrincipal();
        List<String> roles =getRoleFromDb(user);
        List<String> permissions =getPermissionFromDb(user);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    private List<String> getPermissionFromDb(User user) {
        List<String> list = Arrays.asList("order:manager", "order:add", "user:delete");

        return list;

    }

    private List<String> getRoleFromDb(User user) {
        List<String> list = Arrays.asList("admin", "user");
        return list;

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println(authenticationToken);

        String username = (String)authenticationToken.getPrincipal();
        User user=getUserFromDB(username);
        if(user==null){
            throw new UnknownAccountException();
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo
                       (user,
                        user.getPassword(),
                        ByteSource.Util.bytes(user.getSalt()), //盐的处理
                        this.getName());

        return authenticationInfo;
    }

    private User getUserFromDB(String username) {

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        User user = userService.getOne(userQueryWrapper);
        return user;
    }

}
